import { io, Socket } from "socket.io-client";

class SocketService {
  private socket: Socket | null = null;
  private token: string | null = null;

  // 连接 WebSocket
  connect(token: string) {
    console.log("🔌 开始连接WebSocket...");
    this.token = token;

    this.socket = io({
      auth: { token },
      transports: ["websocket", "polling"],
    });

    this.socket.on("connect", () => {
      console.log("✅ WebSocket 连接成功，Socket ID:", this.socket?.id);
    });

    this.socket.on("disconnect", (reason) => {
      console.log("❌ WebSocket 连接断开，原因:", reason);
    });

    this.socket.on("connect_error", (error) => {
      console.error("❌ WebSocket 连接错误:", error);
    });

    this.socket.on("error", (error) => {
      console.error("❌ WebSocket 错误:", error);
    });
  }

  // 断开连接
  disconnect() {
    console.log("🔌 断开WebSocket连接");
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
    }
    this.token = null;
  }

  // 加入聊天室
  joinRoom(chatRoomId: number) {
    if (this.socket) {
      this.socket.emit("joinChatRoom", { chatRoomId });
    }
  }

  // 离开聊天室
  leaveRoom(chatRoomId: number) {
    if (this.socket) {
      this.socket.emit("leaveChatRoom", { chatRoomId });
    }
  }

  // 发送消息
  sendMessage(
    chatRoomId: number,
    content: string,
    type: string = "text",
    replyToId?: number,
    fileData?: any
  ) {
    if (this.socket) {
      this.socket.emit("sendMessage", {
        chatRoomId,
        content,
        type,
        replyToId,
        fileData,
      });
    }
  }

  // 发送打字状态
  sendTyping(chatRoomId: number, isTyping: boolean) {
    if (this.socket) {
      this.socket.emit("typing", { chatRoomId, isTyping });
    }
  }

  // 监听新消息
  onNewMessage(callback: (message: any) => void) {
    if (this.socket) {
      this.socket.on("newMessage", (message) => {
        callback(message);
      });
    }
  }

  // 监听用户加入
  onUserJoin(callback: (data: any) => void) {
    if (this.socket) {
      this.socket.on("userJoined", (data) => {
        callback(data);
      });
    }
  }

  // 监听用户离开
  onUserLeave(callback: (data: any) => void) {
    if (this.socket) {
      this.socket.on("userLeft", (data) => {
        callback(data);
      });
    }
  }

  // 监听连接
  onConnect(callback: () => void) {
    if (this.socket) {
      this.socket.on("connect", () => {
        callback();
      });
    }
  }

  // 监听断开连接
  onDisconnect(callback: () => void) {
    if (this.socket) {
      this.socket.on("disconnect", () => {
        callback();
      });
    }
  }

  // 移除所有监听器
  removeAllListeners() {
    if (this.socket) {
      this.socket.removeAllListeners();
    }
  }

  // 获取连接状态
  isConnected(): boolean {
    const connected = this.socket?.connected || false;
    console.log("🔍 WebSocket连接状态:", connected);
    return connected;
  }

  // 获取Socket实例（用于调试）
  getSocket(): Socket | null {
    return this.socket;
  }
}

// 创建单例实例
const socketService = new SocketService();

export default socketService;
